package com.cs.csworkflow.service.impl;

import com.cs.csworkflow.dbo.FormMain;
import com.cs.csworkflow.dbo.FormNode;
import com.cs.csworkflow.enums.FormMainStatusEnum;
import com.cs.csworkflow.enums.FormNodeStatusEnum;
import com.cs.csworkflow.repository.FormMainRepository;
import com.cs.csworkflow.repository.FormNodeRepository;
import com.cs.csworkflow.service.FormService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class FormServiceImpl implements FormService {
    @Autowired
    private FormMainRepository formMainRepository;
    @Autowired
    private FormNodeRepository formNodeRepository;

    @Override
    public FormMain save(FormMain formMain) {
        formMain.setStatus(FormMainStatusEnum.DRAFT.getCode());
        // 新增状态，设置创建时间
        if (!StringUtils.isEmpty(formMain.getId())) {
            formMain.setCreateTime(new Date());
        }
        FormMain retForm = formMainRepository.save(formMain);
        return retForm;
    }

    @Override
    public FormMain updateStatus(Long id, Integer status) {
        FormMain formMain = formMainRepository.findById(id).get();
        formMain.setStatus(status);
        FormMain retForm = formMainRepository.save(formMain);
        return retForm;
    }

    @Override
    public FormMain findForm(Long id) {
        return formMainRepository.findById(id).get();
    }

    @Override
    @Transactional
    public List<FormNode> setNodes(Long formId, List<FormNode> formNodeList) {
        // 先删除原本的会办节点
        deleteFormNodes(formId);
        // 写入新的会办节点
        for (FormNode formNode : formNodeList) {
            formNode.setFormId(formId);
            formNode.setNodeStat(FormNodeStatusEnum.NOT_READY.getCode());
        }
        List<FormNode> retNodeList = formNodeRepository.saveAll(formNodeList);
        // 设置会办状态为会办中
        updateStatus(formId, FormMainStatusEnum.IN_FLOW.getCode());
        return retNodeList;
    }

    @Override
    public List<FormMain> findFormList(Integer status, String condition, int page, int size) {
        List<FormMain> formList = formMainRepository.findForms(status, condition, page, size);
        return formList;
    }

    private void deleteFormNodes(Long formId) {
        formNodeRepository.deleteFormNodesByFormId(formId);
    }
}
